import Taro, { Component } from '@tarojs/taro'
import { AtActionSheet, AtActionSheetItem } from 'taro-ui'
import classnames from 'classnames'
import PropsType from 'prop-types'
import { View, Image } from '@tarojs/components'
import http from '@/api'
import '../styles/imagesupload.scss'

const itembg = require('../assete/upload_icon.png')
const itemclose = require('./item_close.png')
export default class DImagesupload extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isOpened: false,
      status: true,
      list: [],
      imgSrc: '',
      imgItem: '',
      active: ''
    }
  }

  componentDidMount() {
    this.props.FunCenter(this);
  }

  componentWillMount() {
    let { value, count = 9 } = this.props
    let { list, status } = this.state
    if (value.length > 0) {
      value.map(item => {
        list.push(item)
      })
    }
    if (list.length === count) {
      status = false
    }
    this.setState({
      list,
      status
    })
  }

  onHandleClick = (e) => {
    e.stopPropagation()
    const { statusClk, count } = this.props
    const { list } = this.state
    if (!statusClk) {
      return
    }
    // let { isOpened } = this.state
    // isOpened = !isOpened
    if (count == list.length) {
      this.setState({
        isOpened: false,
        active: ""
      })
    } else {
      this.setState({
        isOpened: true,
        active: ""
      })
    }

  }

  onHanldeClose = (e) => {
    e.stopPropagation()

    let { list, status } = this.state
    let i = e.currentTarget.dataset.i
    list.splice(i, 1)
    if (list.length < 9) {
      status = true
    }
    // 删除图片的操作
    this.setState({
      list,
      status
    }, () => {
      this.props.onChangeImages && this.props.onChangeImages(this.state.list)
    })
  }

  onHandleImages() {
    if (!window.bridge) {
      return
    }
    let { list, active, status } = this.state
    let { count = 9, isWatermark } = this.props
    if (list.length >= count - 1) {
      status = false
    } else {
      status = true
    }
    const _that = this
    window.bridge.callHandler('openCamera', { "isWatermark": isWatermark }, function responseCallback(res) {
      let _data = JSON.parse(res)
      if (_data.length > 0 && !active) {
        list.push({
          ..._data[0]
        })
      } else if (_data.length > 0 && active) {
        list[active] = _data[0]
      } else {
        Taro.showToast({
          icon: "none",
          title: "图片上传失败!"
        })
      }
      // Taro.showToast({
      //     title: '上传图片',
      //     duration: 800
      // }).then(() => {
      _that.setState({
        list,
        status,
        isOpened: false
      }, () => {
        _that.props.onChangeImages && _that.props.onChangeImages(_that.state.list)
      })
      // })
    })
  }



  onLookHandle(e) {
    e.stopPropagation()
    if (this.props.disabled) { return }
    const { statusClk, count } = this.props
    if (!statusClk) {
      return
    }
    // 对应图片的预览
    let i = e.currentTarget.dataset.index
    let { list, imgSrc } = this.state
    imgSrc = list[i].url
    if (window.bridge) {
      let _images = []
      list.map(item => {
        _images.push(item.url)
      })
      window.bridge.callHandler('previewPhoto', { "index": i, "images": _images }, function responseCallback() { })
    } else {
      if (count == list.length) {
        this.setState({
          isOpened: false,
        })
      } else {
        this.setState({
          isOpened: true,
          imgSrc,
          active: i
        })
      }
    }
  }

  onHandleLook() {
    let { imgSrc } = this.state
    this.setState({
      imgItem: imgSrc
    })
  }

  onHandleCencal(e) {
    e.stopPropagation()
    this.setState({
      imgSrc: "",
      imgItem: ""
    })

  }
  onUploadImage(res) {
    let request, type

    if (this.props.isWatermark) {
      request = http.uploadImagesWatermark
    } else {
      request = http.uploadImages
    }

    return new Promise((resolve, rejects) => {
      fetch(res.tempFilePaths[0])
      .then(res => res.blob())
      .then(blob => {
          type = blob.type.split("/")[1]
          // 获取图片类型
          request(res.tempFilePaths[0], type)
            .then(data => {
              let _data = JSON.parse(data)
              if (+_data.code === 0) {
                resolve(_data.data)
              } else if (+_data.code === -1){
                rejects(_data.msg)
              }
              rejects('网络异常！')
            })
            .catch(() => {
              rejects('网络异常')
            })
        })
    })

  }

  onHandleItem() {
    let { count = 9, isWatermark } = this.props

    let { list, status, active } = this.state
    if (list.length >= count - 1) {
      status = false
    } else {
      status = true
    }
    if (window.bridge) {
      const _that = this
      if (active) {
        count = 1
      } else if (list.length > 0 && !active && (count - list.length > 0)) {
        count = count - list.length
      }
      window.bridge.callHandler('openGalary', { 'count': Number(count) + '', "isWatermark": isWatermark }, function responseCallback(res) {
        let _data = JSON.parse(res)

        if (_data.length > 0) {
          // 对单个和多个图片进行添加
          if (active !== '' && count === 1) {
            list[active] = _data[0]
          } else if (active && count > 1) {
            list[active] = _data[0]
          } else {
            _data.map(item => {
              list.push({
                ...item
              })
            })
          }

          _that.setState({
            list,
            status,
            isOpened: false
          }, () => {
            _that.props.onChangeImages && _that.props.onChangeImages(_that.state.list)
          })

        } else {
          Taro.showToast({
            icon: "none",
            title: "图片上传失败!"
          })
        }
      })
    } else {
      Taro.chooseImage({
        count
      }).then(res => {
        this.onUploadImage(res).then(data => {
          // 对单个和多个图片进行添加
          if (active !== '' && count === 1) {
            list[active] = data
          } else if (active && count > 1) {
            list[active] = data
          } else {
            list.push(data)
          }
          this.setState({
            list,
            status,
            isOpened: false
          }, () => {
            this.props.onChangeImages && this.props.onChangeImages(this.state.list)
          })

        })
          .catch(err => {
            Taro.showToast({
              icon: "none",
              title: err
            })
          })
      })
    }
  }
  render() {
    const {
      isOpened,
      list,
      status,
      imgSrc,
      imgItem
    } = this.state
    const {
      className,
      bgImage,
      text,
      count,
      statusClk,
      disabled
    } = this.props
    return (
      <View className={classnames('b_imagesupload', className)} onClick={this.onHandleClick.bind(this)}>
        <View className='b_imagesupload__images'>
          {
            list && list.map((item, i) => {
              return <View key={i} className={classnames('b_imagesupload__images_item', bgImage ? 'item_bgImage__width' : '')}>
                <Image src={item.url} className='list_item__images' data-index={i} onClick={this.onLookHandle.bind(this)}></Image>
                {
                  statusClk && !disabled && <Image className='list_item__close' data-i={i} src={itemclose} onClick={this.onHanldeClose.bind(this)}></Image>
                }
                {/* <Image className='list_item__close' data-i={i} src={itemclose} onClick={this.onHanldeClose.bind(this)}></Image> */}
              </View>
            })
          }
          {
            ((!bgImage && status) && (list.length !== count)) && <View className='b_imagesupload__upload'>
              <Image src={itembg} className='b_imagesupload__upload_bg'></Image>
              <View className='b_imagesupload__upload_text'>上传照片</View>
            </View>
          }
          {
            ((bgImage && status) && (list.length !== count)) && <View className='b_imagesupload__bgImage'>
              <Image src={bgImage} className='b_imagesupload__bgImage_bg'></Image>
              <View className='b_imagesupload__bgImage_text'>{text}</View>
            </View>
          }
        </View>
        <AtActionSheet isOpened={isOpened} cancelText={'取消'}>
          <View className='b_imagesupload__title'>
            <View className='b_imagesupload__title_text'>请选择照片</View>
            <AtActionSheetItem onClick={this.onHandleImages.bind(this)}>拍照</AtActionSheetItem>
            <AtActionSheetItem onClick={this.onHandleItem.bind(this)}>从相册选择</AtActionSheetItem>
            {
              imgSrc && <AtActionSheetItem onClick={this.onHandleLook.bind(this)}>查看大图</AtActionSheetItem>
            }
          </View>
        </AtActionSheet>
        {
          imgItem && <View className='b_imagesupload__look' onClick={this.onHandleCencal.bind(this)}>
            <Image src={imgItem} className='b_imagesupload__look_item'></Image>
          </View>
        }
      </View>
    )
  }
}

DImagesupload.defaultProps = {
  className: '',
  bgImage: '',
  count: 9,
  text: '',
  value: [],
  statusClk: true,
  isWatermark: false,
  disabled: false,
  onChangeImages: () => { },
  FunCenter: () => {}
}

DImagesupload.PropsType = {
  className: PropsType.oneOfType[PropsType.string, PropsType.object],
  bgImage: PropsType.string,
  count: PropsType.number,
  text: PropsType.string,
  value: PropsType.array,
  statusClk: PropsType.bool,
  isWatermark: PropsType.bool,
  onChangeImages: PropsType.func,
  FunCenter: PropsType.func
}
